﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using AmkeniCrossLoginApplication.Data_Access;
using AjaxControlToolkit;

//Used to send an email address
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Drawing;
using System.Security.AccessControl;
using System.IO;
using System.Security.Principal;

namespace Amkeni_System.CO
{
    public partial class ApprovedProjectReport : System.Web.UI.Page
    {
        int proj;
        int rprt;
        int yr;
        int rfp;
        Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();

        protected void Page_PreInit(object sender, EventArgs e)
        {
            /*if (User.IsInRole("IP"))
            {
                MasterPageFile = "~/MasterPages/Project.Master";
            }
            if (User.IsInRole("Programme"))
            {
                MasterPageFile = "~/MasterPages/Programme.Master";
            }
            if (User.IsInRole("Administrator"))
            {
                MasterPageFile = "~/MasterPages/CO.Master";
            }
            if (User.IsInRole("IP") && User.IsInRole("Programme"))
            {
                MasterPageFile = "~/MasterPages/ProgProject.Master";
            }*/
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            if (Session["App_Project"] != null && Session["App_ReportPeriod"] != null && Session["App_Year"] != null && Session["App_Call"] != null)
            {
                proj = (int)Session["App_Project"];
                rprt = (int)Session["App_ReportPeriod"];
                yr = (int)Session["App_Year"];
                rfp = (int)Session["App_Call"];

                //populateOutputIndicator("1.1.1");
                populateListofDonors(proj, rprt, yr, rfp);

                populateReport(proj, rprt, yr, rfp);
            }
            else
            {
                Response.Redirect("~/Amkeni_System/CO/Approved_Project_Reports.aspx");
            }
        }
//===================================================================================================================
        protected void Page_Load(object sender, EventArgs e)
        {
            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    var ipName = (from p in db.implementing_partner
                                    where p.ip_id == proj
                                    select p.name).FirstOrDefault();
                    var periodName = (from r in db.report_period
                                        where r.report_period_id == rprt
                                        select r.period).FirstOrDefault();
                    var yearName = (from y in db.years
                                    where y.year_id == yr
                                    select y.year1).FirstOrDefault();
                    var rfpName = (from r in db.RFPs
                                   where r.RFP_id == rfp
                                   select r.RFP_name).FirstOrDefault();

                    CallLabel.Text = rfpName;
                    ProjectLabel.Text = ipName;
                    YearLabel.Text = periodName;
                    ReportPeriodLabel.Text = yearName.ToString();

                    ToolkitScriptManager1.CompositeScript.Scripts.Add(new ScriptReference("~/Amkeni_System/Scripts/CounterScript.js"));

                    //populateListofDonors(proj, rprt, yr);
                    if (!Page.IsPostBack)
                    {
                        //This allows saving of any changes made to the project authors
                        PhotoCount(proj, rprt, yr, rfp);
                        generateCumulativeFinancialSummaryPieChart(proj, rprt, yr, rfp);
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//============================================================================================================
        protected void generateCumulativeFinancialSummaryPieChart(int aproj, int arprt, int ayr, int acall)
        {
            var reportData = (from data in db.ip_report
                              where
                              data.ip_id == aproj &&
                              data.year_id == ayr &&
                              data.report_period_id == arprt &&
                              data.RFP_id == acall
                              select data).FirstOrDefault();

            //Cummulative Financial Summary
            IQueryable _approvedBudget = null;
            if (reportData.RFP.RFP_name == "Amkeni Wakenya" || reportData.implementing_partner.abbreviation == "Amkeni Wakenya")
            {
                _approvedBudget = (from data in db.monitoring_plan
                                   where
                                   data.ip_id == aproj &&
                                   data.year_id == ayr &&
                                   data.RFP_id == acall
                                   select data.resource_required);
            }
            else
            {
                _approvedBudget = (from data in db.monitoring_plan
                                   where
                                   data.ip_id == aproj &&
                                   data.RFP_id == acall
                                   select data.resource_required);
            }

            decimal budget = 0;
            foreach (decimal approvedBudget in _approvedBudget)
            {
                budget += approvedBudget;
            }
            ApprovedBudgetTextBox.Text = budget.ToString("N2");
            ApprovedBudgetTextBox.ReadOnly = true;

            decimal expenditure = 0;
            expenditure = reportData.total_cfs.HasValue ? reportData.total_cfs.Value : 0;

            if (reportData.total_cfs != null)
            {
                FinancialSummaryPieChart.PieChartValues.Add(new AjaxControlToolkit.PieChartValue
                {
                    Category = "Total Expenditure",
                    Data = expenditure,
                    PieChartValueColor = "#6C1E83",
                    PieChartValueStrokeColor = "black"
                });

                FinancialSummaryPieChart.PieChartValues.Add(new AjaxControlToolkit.PieChartValue
                {
                    Category = "Balance of Funds",
                    Data = budget - expenditure,
                    PieChartValueColor = "#D08AD9",
                    PieChartValueStrokeColor = "black"
                });
            }
        }
//============================================================================================================
        protected void populateReport(int aproj, int arprt, int ayr, int acall)
        {
            try
            {
                //Important, used to find the controls at page_init above
                ReportsAccordion.FindControl("nothing");

                var reportData = (from data in db.ip_report
                                  where
                                  data.ip_id == aproj &&
                                  data.year_id == ayr &&
                                  data.report_period_id == arprt &&
                                  data.RFP_id == rfp
                                  select data).FirstOrDefault();

                if (reportData != null)
                {
                    AuthorTextBox.Text = reportData.project_editor;
                    CATextBox.Text = reportData.project_context;
                    IndirectBeneficiariesTextBox.Text = reportData.beneficiaries.ToString();
                    RecommendationsTextBox.Text = reportData.recommendations;
                    LessonsTextBox.Text = reportData.lessons;
                    ChallengesTextBox.Text = reportData.challenges;
                    GenderMainstreamingTextBox.Text = reportData.gender_mainstreaming;
                    PartnershipsTextBox.Text = reportData.partnerships;

                    //Cummulative Financial Summary
                    var _approvedBudget = (from data in db.monitoring_plan
                                           where
                                           data.ip_id == aproj &&
                                           data.year_id == ayr &&
                                           data.RFP_id == acall
                                           select data.resource_required);
                    decimal budget = 0;
                    foreach (decimal approvedBudget in _approvedBudget)
                    {
                        budget += approvedBudget;
                    }
                    ApprovedBudgetTextBox.Text = budget.ToString("N2");
                    ApprovedBudgetTextBox.ReadOnly = true;

                    //ApprovedBudgetTextBox.Text = reportData.approved_budget_cfs.HasValue ? reportData.approved_budget_cfs.Value.ToString() : string.Empty;
                    TotalTextBox.Text = reportData.total_cfs.HasValue ? reportData.total_cfs.Value.ToString() : string.Empty;
                    BalanceLabel.Text = reportData.balance_cfs.HasValue ? reportData.balance_cfs.Value.ToString() : string.Empty;
                    DeliveryLabel.Text = reportData.delivery_cfs.HasValue ? reportData.delivery_cfs.Value.ToString() + "%" : string.Empty;
                }

                var theStory = (from data in db.success_story
                                where
                                    data.ip_id == aproj &&
                                    data.report_period_id == arprt &&
                                    data.year_id == ayr &&
                                    data.RFP_id == rfp
                                select data).FirstOrDefault();

                if (theStory != null)
                {
                    TitleTxbx.Text = theStory.title.Trim();
                    ContextTxbx.Text = theStory.context.Trim();
                    ProblemTxbx.Text = theStory.problem.Trim();
                    InterventionTxbx.Text = theStory.intervention.Trim();
                    ResultsTxbx.Text = theStory.result.Trim();
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//============================================================================================================
        protected void PhotoCount(int ip, int rp, int yr, int thecall)
        {
            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                int photoCount = (from data in db.ip_photo
                                  where data.ip_id == ip && data.report_period_id == rp
                                      && data.year_id == yr && data.RFP_id == thecall
                                  select data).Count();
                if (photoCount >= 3)
                {
                    PhotoUpload.Enabled = false;
                }
                else
                {
                    PhotoUpload.Enabled = true;
                }
            }
        }
//============================================================================================================
        protected void EditorButton_Click(object sender, EventArgs e)
        {
            try
            {
                Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();

                ip_report editors = db.ip_report.SingleOrDefault(
                                        pr => pr.ip_id == proj &&
                                        pr.year_id == yr &&
                                        pr.report_period_id == rprt &&
                                        pr.RFP_id == rfp);

                if (AuthorTextBox.Text == String.Empty)
                {
                    Label40.Text = "*Please enter all contributers";
                    Label40.ForeColor = System.Drawing.Color.Red;
                }

                if (editors != null)
                {
                    editors.project_editor = AuthorTextBox.Text;
                    db.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//============================================================================================================
        protected void populateListofDonors(int aproj, int arprt, int ayr, int acall)
        {
            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    ReportsAccordion.FindControl("nothing");

                    var reports_under_donors = (from d in db.donor_report_match
                                                where d.ip_id == aproj &&
                                                d.report_period_id == arprt &&
                                                d.year_id == ayr &&
                                                d.RFP_id == acall
                                                select d);

                    List<donor> allDonors = (from d in db.donors select d).ToList();

                    List<donor> addDonors = new List<donor>();

                    foreach (var reportDonorData in reports_under_donors)
                    {
                        foreach (donor donorData in allDonors.ToList())
                        {
                            if (donorData.donor_id == reportDonorData.donor_id)
                            {
                                addDonors.Add(donorData);
                                allDonors.Remove(donorData);
                            }
                        }
                    }
                    ProjectDonorListBox.DataSource = addDonors;
                    ProjectDonorListBox.DataBind();

                    DonorListBox.DataSource = allDonors;
                    DonorListBox.DataBind();
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//============================================================================================================
        protected void SaveDonorButton_Click(object sender, EventArgs e)
        {
            try
            {
                Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();

                //==========================================+
                //  Add a new donor report match Record     |
                //==========================================+
                foreach (ListItem li in DonorListBox.Items)
                {
                    if (li.Selected == true)
                    {
                        donor_report_match newDRMatch = new donor_report_match();
                        newDRMatch.ip_id = proj;
                        newDRMatch.report_period_id = rprt;
                        newDRMatch.year_id = yr;
                        newDRMatch.RFP_id = rfp;
                        newDRMatch.donor_id = int.Parse(li.Value.Trim());
                        db.donor_report_match.Add(newDRMatch);
                        db.SaveChanges();
                    }

                }
                populateListofDonors(proj, rprt, yr, rfp);
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//============================================================================================================
        protected void DeleteDonorButton_Click(object sender, EventArgs e)
        {
            try
            {
                Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();
                //=======================================+
                //  Delete donor report match Record     |
                //=======================================+
                foreach (ListItem li in ProjectDonorListBox.Items)
                {
                    if (li.Selected)
                    {
                        int donorID = int.Parse(li.Value.Trim());
                        donor_report_match matchingDonor = db.donor_report_match.Single(
                            data => data.donor_id == donorID && data.ip_id == proj && data.report_period_id == rprt
                            && data.year_id == yr && data.RFP_id == rfp);
                        db.donor_report_match.Remove(matchingDonor);
                        db.SaveChanges();
                    }
                }
                populateListofDonors(proj, rprt, yr, rfp);
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//===============================================================================================================
        protected void CAButton_Click(object sender, EventArgs e)
        {
            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    var c = (from ca in db.ip_report
                             where ca.ip_id == proj &&
                             ca.year_id == yr && ca.report_period_id == rprt && ca.RFP_id == rfp
                             select ca.project_context).FirstOrDefault();

                    //=========================================+
                    //  UPDATE the IP Report Record Record     |
                    //=========================================+
                    ip_report caReport = db.ip_report.SingleOrDefault(
                                                ca_1 => ca_1.ip_id == proj &&
                                                ca_1.year_id == yr &&
                                                ca_1.report_period_id == rprt && ca_1.RFP_id == rfp);

                    caReport.project_context = CATextBox.Text.Trim();
                    db.SaveChanges();

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void IB_Btn_Click(object sender, EventArgs e)
        {
            Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();

            try
            {
                var c = (from ca in db.ip_report
                         where ca.ip_id == proj &&
                         ca.year_id == yr && ca.report_period_id == rprt && ca.RFP_id == rfp
                         select ca.beneficiaries).FirstOrDefault();

                //==================================+
                //  UPDATE the IP Report Record     |
                //==================================+
                ip_report beneficairyReport = db.ip_report.SingleOrDefault(
                                            ca_1 => ca_1.ip_id == proj &&
                                            ca_1.year_id == yr &&
                                            ca_1.report_period_id == rprt &&
                                            ca_1.RFP_id == rfp);

                beneficairyReport.beneficiaries = int.Parse(IndirectBeneficiariesTextBox.Text.Trim());
                db.SaveChanges();

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//===============================================================================================================
        int Maletotal = 0;
        int Femaletotal = 0;
        int Malecount = 0;
        int FemaleCount = 0;
        protected void BeneficiaryGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblMaleCount = (Label)e.Row.FindControl("MaleCount");
                TextBox txtMaleCount = (TextBox)e.Row.FindControl("TextBox2");
                if (lblMaleCount == null)
                {
                    Malecount = int.Parse(txtMaleCount.Text.Trim());
                }
                else if (txtMaleCount == null)
                {
                    Malecount = int.Parse(lblMaleCount.Text.Trim());
                }
                Maletotal = Maletotal + Malecount;

                Label lblFemaleCount = (Label)e.Row.FindControl("FemaleCount");
                TextBox txtFemaleCount = (TextBox)e.Row.FindControl("TextBox3");
                if (lblFemaleCount == null)
                {
                    FemaleCount = int.Parse(txtFemaleCount.Text.Trim());
                }
                else if (txtFemaleCount == null)
                {
                    FemaleCount = int.Parse(lblFemaleCount.Text.Trim());
                }
                Femaletotal = Femaletotal + FemaleCount;
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                Label lblMaleTotal = (Label)e.Row.FindControl("MaleTotal");
                lblMaleTotal.Text = Maletotal.ToString();

                Label lblFemaleTotal = (Label)e.Row.FindControl("FemaleTotal");
                lblFemaleTotal.Text = Femaletotal.ToString();

                Label lblGrandTotal = (Label)e.Row.FindControl("GrandTotal");
                lblGrandTotal.Text = (Maletotal + Femaletotal).ToString();
            }
        }
//============================================================================================================
        //WORKING PERFECTLY
        protected void RecommendationsButton_Click(object sender, EventArgs e)//RecommendationsPane
        {
            try
            {
                Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();
                ip_report recommendation = db.ip_report.SingleOrDefault(
                                            pr => pr.ip_id == proj &&
                                            pr.year_id == yr &&
                                            pr.report_period_id == rprt && pr.RFP_id == rfp);
                if (recommendation != null)
                {
                    recommendation.recommendations = RecommendationsTextBox.Text;
                    db.SaveChanges();
                }
                else if (recommendation == null)
                {
                    Response.Redirect("~/Amkeni_System/Project/Saved_Projects/");
                }


            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//===============================================================================================================
        protected void LessonButton_Click(object sender, EventArgs e)
        {
            try
            {
                Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();
                ip_report l = db.ip_report.SingleOrDefault(
                                            pr => pr.ip_id == proj &&
                                            pr.year_id == yr &&
                                            pr.report_period_id == rprt && pr.RFP_id == rfp);
                if (l != null)
                {
                    l.lessons = LessonsTextBox.Text;
                    db.SaveChanges();
                }
                else if (l == null)
                {
                    Response.Redirect("~/Amkeni_System/Project/Saved_Projects/");
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//==============================================================================================================
        protected void successStoryBtn_Click(object sender, EventArgs e)
        {
            try
            {
                Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();

                var story = (from data in db.success_story
                             where data.ip_id == proj
                             && data.report_period_id == rprt
                             && data.year_id == yr
                             && data.RFP_id == rfp
                             select data).FirstOrDefault();
                if (story == null)
                {
                    //==============================+
                    //  Add a new Success Story     |
                    //==============================+
                    success_story theStory = new success_story();
                    theStory.ip_id = proj;
                    theStory.report_period_id = rprt;
                    theStory.year_id = yr;
                    theStory.RFP_id = rfp;
                    theStory.title = TitleTxbx.Text.Trim();
                    theStory.context = ContextTxbx.Text.Trim();
                    theStory.problem = ProblemTxbx.Text.Trim();
                    theStory.intervention = InterventionTxbx.Text.Trim();
                    theStory.result = ResultsTxbx.Text.Trim();

                    db.success_story.Add(theStory);
                    db.SaveChanges();
                }
                else if (story != null)
                {
                    //======================================+
                    //  Update the Success Story Record     |
                    //======================================+
                    success_story theStory = db.success_story.SingleOrDefault(
                        data => data.ip_id == proj &&
                        data.report_period_id == rprt &&
                        data.year_id == yr && data.RFP_id == rfp);

                    theStory.title = TitleTxbx.Text.Trim();
                    theStory.context = ContextTxbx.Text.Trim();
                    theStory.problem = ProblemTxbx.Text.Trim();
                    theStory.intervention = InterventionTxbx.Text.Trim();
                    theStory.result = ResultsTxbx.Text.Trim();
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//==============================================================================================================
        protected void UpcomingActivitiesBtn_Click(object sender, EventArgs e)
        {
            Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();
            try
            {
                //==================================+
                //  Add a new upcoming activity     |
                //==================================+
                upcoming_activities newActivity = new upcoming_activities();
                newActivity.ip_id = proj;
                newActivity.report_period_id = rprt;
                newActivity.year_id = yr;
                newActivity.RFP_id = rfp;
                newActivity.venue = VenueTxBx.Text.Trim();
                newActivity.activity = ActivityTxBx.Text.Trim();
                newActivity.date = DateTime.Parse(DateTxBx.Text.Trim());
                db.upcoming_activities.Add(newActivity);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
            UpcomingActivitiesUpdatePanel.FindControl("UpcomingActivitiesGridView").DataBind();
        }
//==============================================================================================================
        /*protected void populateUpcomingQuarter(int qproj, int qrprt, int qyr)
        {
            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    var uQuarter = (from pr in db.ip_report
                                    where pr.ip_id == qproj &&
                                    pr.year_id == qyr && pr.report_period_id == qrprt
                                    select pr.upcoming_quarter).FirstOrDefault();

                    UpcomingQuarterPane.FindControl("UpcomingQuarterTextBox");
                    UpcomingQuarterTextBox.Text = uQuarter;
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void QuarterButton_Click(object sender, EventArgs e)
        {
            try
            {
                Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();
                ip_report uq = db.ip_report.SingleOrDefault(
                                            pr => pr.ip_id == proj &&
                                            pr.year_id == yr &&
                                            pr.report_period_id == rprt);
                if (uq != null)
                {
                    uq.upcoming_quarter = UpcomingQuarterTextBox.Text.Trim();
                    db.SaveChanges();
                }
                else if (uq == null)
                {
                    Response.Redirect("~/Amkeni_System/Programme/Submitted_Project_Reports/");
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
            populateUpcomingQuarter(proj, rprt, yr);
        }*/
//===============================================================================================================
        protected void SavePhotoBtn_Click(object sender, EventArgs e)
        {
            Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();
            if (PhotoUpload.HasFile)
            {
                try
                {
                    if (PhotoUpload.PostedFile.ContentType == "image/jpeg")
                    {
                        if (PhotoUpload.PostedFile.ContentLength < 5000000)
                        {
                            string filename = Path.GetFileName(PhotoUpload.FileName);
                            filename = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString();

                            string path = "~/Amkeni_System/ip_photos/";

                            PhotoUpload.SaveAs(Server.MapPath(Path.Combine(path, filename + Path.GetExtension(PhotoUpload.FileName))));
                            //PhotoUpload.SaveAs(Server.MapPath("~/Amkeni_System/ip_photos/") + filename + Path.GetExtension(PhotoUpload.FileName));

                            ip_photo newPhoto = new ip_photo();
                            newPhoto.ip_id = proj;
                            newPhoto.report_period_id = rprt;
                            newPhoto.year_id = yr;
                            newPhoto.RFP_id = rfp;
                            newPhoto.caption = CaptionTxBx.Text.Trim();
                            newPhoto.name = filename + Path.GetExtension(PhotoUpload.FileName);

                            db.ip_photo.Add(newPhoto);
                            db.SaveChanges();
                        }
                        else
                        {
                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", "alert('Make sure that the Photograph is less than 5MB')", true);
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", "alert('Make sure that you are uploading a JPEG image only')", true);
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", "alert('Select a photograph to upload')", true);
            }
            PhotoGridView.DataBind();
            PhotoCount(proj, rprt, yr, rfp);
        }
//===============================================================================================================
        protected void ChallengesButton_Click(object sender, EventArgs e)
        {
            try
            {
                Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();
                ip_report pc = db.ip_report.SingleOrDefault(
                                            pr => pr.ip_id == proj &&
                                            pr.year_id == yr &&
                                            pr.report_period_id == rprt &&
                                            pr.RFP_id == rfp);
                if (pc != null)
                {
                    pc.challenges = ChallengesTextBox.Text;
                    db.SaveChanges();
                }
                else if (pc == null)
                {
                    Response.Redirect("~/Amkeni_System/Project/Saved_Projects/");
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//===============================================================================================================
        protected void CrossCuttingBtn_Click(object sender, EventArgs e)
        {
            try
            {
                ip_report crossCuttingIssues = db.ip_report.SingleOrDefault(
                                                data => data.ip_id == proj &&
                                                data.year_id == yr &&
                                                data.report_period_id == rprt &&
                                                data.RFP_id == rfp);
                if (crossCuttingIssues != null)
                {
                    crossCuttingIssues.gender_mainstreaming = GenderMainstreamingTextBox.Text.Trim();
                }
                else if (crossCuttingIssues == null)
                {
                    Response.Redirect("~/Amkeni_System/Project/Saved_Projects/");
                }
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
            finally
            {
                db.SaveChanges();
            }
        }
//===============================================================================================================
        /*protected void populateOutputIndicator(string cpdID)
        {
            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    var indicator = (from c in db.programme_output_indicator
                                     where c.output_indicator_id == cpdID
                                     select c.name).FirstOrDefault();

                    if (indicator == null)
                    {
                        //Important...Used at the Page_Init stage above
                        OutputIndicatorPane.FindControl("TextBox6");
                        TextBox6.Text = null;
                    }
                    else
                    {
                        //Important...Used at the Page_Init stage above
                        OutputIndicatorPane.FindControl("TextBox6");
                        TextBox6.Text = indicator;
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void OutputIndicatorList_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    var cpd = (from c in db.programme_output_indicator
                               where c.output_indicator_id == OutputIndicatorList.SelectedValue
                               select c.name).FirstOrDefault();

                    if (cpd == null)
                    {
                        TextBox6.Text = null;
                    }
                    else
                    {
                        TextBox6.Text = cpd;
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }*/
//===============================================================================================================
        protected void OutputGridView_DataBound(object sender, EventArgs e)
        {
            for (int i = 0; i <= OutputGridView.Rows.Count - 1; i++)
            {
                try
                {
                    Label statusLabel = (Label)OutputGridView.Rows[i].FindControl("StatusLabel");

                    if (statusLabel.Text == "Completed")
                    {
                        OutputGridView.Rows[i].Cells[3].BackColor = Color.Green;
                    }
                    else if (statusLabel.Text == "Ongoing")
                    {
                        OutputGridView.Rows[i].Cells[3].BackColor = Color.Yellow;
                    }
                    else if (statusLabel.Text == "Delayed" || statusLabel.Text == "N/A")
                    {
                        OutputGridView.Rows[i].Cells[3].BackColor = Color.Red;
                    }
                }
                catch (Exception ex)
                {
                    return;
                }
            }
        }
//===============================================================================================================
        protected void OutputIndicatorList_DataBound(object sender, EventArgs e)
        {
            Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();
            DropDownList ddl = sender as DropDownList;
            if (ddl != null)
            {
                foreach (ListItem li in ddl.Items)
                {
                    string id = li.Value.Trim();
                    string indicator = (from data in db.indicators
                                        where data.output_indicator_id == id
                                        select data.name).FirstOrDefault();
                    li.Attributes["title"] = indicator;
                }
            }
        }
//===============================================================================================================
        protected void OutputGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //((Button)e.Row.Cells[6].Controls[0]).OnClientClick =
                //    "if (!confirm('Do you really want to delete?')) return;";

                // loop all data rows
                foreach (DataControlFieldCell cell in e.Row.Cells)
                {
                    // check all cells in one row
                    foreach (Control control in cell.Controls)
                    {
                        // Must use LinkButton here instead of ImageButton
                        // if you are having Links (not images) as the command button.
                        Button button = control as Button;
                        if (button != null && button.CommandName == "Delete")
                            // Add delete confirmation
                            button.OnClientClick = "if (!confirm('Are you sure " +
                                   "you want to delete this record?')) return;";
                    }
                }
            }
        }
//===============================================================================================================
        protected void OutputGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = OutputGridView.Rows[e.RowIndex];

            DropDownList cpdList = (DropDownList)row.FindControl("DropDownList2");
            string result_id = cpdList.SelectedValue;

            Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();
            try
            {
                var result = (from data in db.indicator_result
                              where data.ip_id == proj &&
                              data.year_id == yr &&
                              data.report_period_id == rprt &&
                              data.RFP_id == rfp &&
                              data.indicator_id == int.Parse(result_id.Trim())
                              select data).FirstOrDefault();//FirstOrDefault() is important as it won't
                //do a selection without it.
                if (result != null)
                {
                    string alert = "<script language='javascript' type='text/javascript'>alert('That output indicator has already been answered');</script>";
                    ScriptManager.RegisterClientScriptBlock(this,
                        GetType(),
                        "alert",
                        alert,
                        false);
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
//===============================================================================================================
        /*protected void clearOutputSelectors()
        {
            OutputIndicatorList.SelectedIndex = 0;
            CpdOutputResultTextBox.Text = null;
            CpdOutputCommentTextBox.Text = null;
        }
//===============================================================================================================
        protected void OutputButton_Click(object sender, EventArgs e)
        {
            string output_indicator_id = OutputIndicatorList.SelectedValue;

            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    var output_result = (from result in db.output_indicator_result
                                         where result.ip_id == proj &&
                                         result.year_id == yr &&
                                         result.report_period_id == rprt &&
                                         result.output_indicator_id == output_indicator_id
                                         select result).FirstOrDefault();//FirstOrDefault() is important as it won't
                    //do a selection without it.

                    if (output_result == null)
                    {
                        //=====================================+
                        //  Add a new Output_Result Record     |
                        //=====================================+
                        output_indicator_result newResult = new output_indicator_result();
                        newResult.ip_id = proj;
                        newResult.year_id = yr;
                        newResult.report_period_id = rprt;
                        newResult.output_indicator_id = output_indicator_id;
                        newResult.result = CpdOutputResultTextBox.Text;
                        newResult.comment = CpdOutputCommentTextBox.Text;
                        newResult.submission_date = DateTime.Now;

                        db.output_indicator_result.Add(newResult);
                        db.SaveChanges();
                    }
                    else if (output_result != null)
                    {
                        ClientScript.RegisterStartupScript(
                            this.GetType(),
                            "myalert",
                            "alert('That output indicator has already been reported against');",
                            true);
                        return;
                    }

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            clearOutputSelectors();
            populateOutputIndicator("1.1.1");
            OutputUpdatePanel.FindControl("OutputGridView").DataBind();
        }*/
//===============================================================================================================
        /*protected void ProjectCommentButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["App_Project"];
            long rprt = (long)Session["App_ReportPeriod"];
            long yr = (long)Session["App_Year"];

            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    //===================================================+
                    //  UPDATE the comment Record in project_reports     |
                    //===================================================+
                    project_reports pr = db.project_reports.SingleOrDefault(
                                            myPr => myPr.project_id == proj &&
                                            myPr.year_id == yr &&
                                            myPr.report_period_id == rprt);

                    pr.comment = ProjectCommentTextBox.Text;
                    db.SaveChanges();

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": Project Comment added by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            populateProjectCommentTextbox(proj, rprt, yr);
        }*/
//===============================================================================================================
        protected void ReturnButton_Click(object sender, EventArgs e)
        {
             //Revert saved == false and put submitted == true

            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    ip_report pr = db.ip_report.SingleOrDefault(
                                            myPr => myPr.ip_id == proj &&
                                            myPr.year_id == yr &&
                                            myPr.report_period_id == rprt &&
                                            myPr.RFP_id == rfp);

                    pr.submitted = true;
                    pr.approved = false;
                    pr.report_status_id = 1;

                    db.SaveChanges();

                    //=============================================+
                    //  Send Email Message to Programme People     |
                    //=============================================+

                    //Create the mail message
                    MailMessage mail = new MailMessage();

                    //Add multiple addresses
                    var prog_email = (from data in db.users
                                      where data.active == true && data.send_email == true && data.region != null 
                                      select new
                                      {
                                          data.region,
                                          data.email
                                      });

                    var region = (from data in db.implementing_partner
                                        where data.ip_id == proj
                                        select new
                                        {
                                            data.region.region_id
                                        }).Single();

                    foreach (var savedUser in prog_email)
                    {
                        string[] theUser = savedUser.region.Split(new Char[] { ',' });
                        if (theUser != null)
                        {
                            foreach (string aUser in theUser)
                            {
                                if (aUser == region.region_id.ToString().Trim())
                                {
                                    mail.To.Add(savedUser.email.Trim());
                                }
                            }
                        }
                    }

                    //Set the content
                    mail.Subject = "Monitoring and Evaluation: Reporting System";

                    System.Text.StringBuilder sbuilder = new System.Text.StringBuilder();
                    sbuilder.Append("Dear programme team,").AppendLine().AppendLine();
                    sbuilder.Append("Please note that the PMU has returned the ");
                    sbuilder.Append(pr.implementing_partner.name.Trim() + " " +
                        pr.report_period.period.Trim() + " " + pr.year.year1.ToString().Trim());
                    sbuilder.Append(" quarterly report to you for updating.").AppendLine().AppendLine();

                    if (ProjectCommentTextBox.Text != string.Empty)
                    {
                        sbuilder.Append("CO comments include: ");
                        sbuilder.Append(ProjectCommentTextBox.Text).AppendLine().AppendLine();
                    }

                    sbuilder.Append("You can access the system here: http://undpke01wa001.azurewebsites.net/Amkeni_System/Programme/Submitted_Project_Reports.aspx ").AppendLine().AppendLine();
                    sbuilder.Append("Thank you").AppendLine().AppendLine();
                    sbuilder.Append("M&E team").AppendLine().AppendLine().AppendLine();
                    sbuilder.Append("*This email is automatically generated - please do not reply").AppendLine();

                    mail.Body = sbuilder.ToString();

                    //Send the message
                    SmtpClient smtp = new SmtpClient();
                    /****SMTP Client is defined in the Web.Config File****/

                    ServicePointManager.ServerCertificateValidationCallback = delegate(
                            object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                    { return true; }; //Always Accept
                    try
                    {
                        smtp.Send(mail);
                    }
                    catch (Exception ex)
                    {
                        ErrorLabel.Text = "MSG NOT SENT " + ex.Message + " " + ex.StackTrace;
                    }

                    //=============================================+
                    //                  END SEND MAIL              |
                    //=============================================+

                    Session["App_Project"] = null;
                    Session["App_ReportPeriod"] = null;
                    Session["App_Year"] = null;
                    Session["App_Call"] = null;

                    Response.Redirect("~/Amkeni_System/Programme/Submitted_Project_Reports.aspx");
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            Session["App_Project"] = null;
            Session["App_ReportPeriod"] = null;
            Session["App_Year"] = null;
            Session["App_Call"] = null;
        }
//===============================================================================================================
        protected void Return2ProjectButton_Click(object sender, EventArgs e)
        {
             //Revert saved == false and put submitted == true
           

            /*using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    project_reports pr = db.project_reports.SingleOrDefault(
                                            myPr => myPr.project_id == proj &&
                                            myPr.year_id == yr &&
                                            myPr.report_period_id == rprt);

                    pr.saved = true;
                    pr.approved = false;
                    pr.project_status_id = 1;

                    db.SaveChanges();



                    //===========================================+
                    //  Send Email Message to Project People     |
                    //===========================================+

                    //Create the mail message
                    MailMessage mail = new MailMessage();

                    //Set the addresses and specify a friendly 'from' name
                    mail.From = new MailAddress("monitoring.so@undp.org", "M&E");
                    const string fromPassword = "Monitoring2012";

                    //Add multiple addresses
                    var proj_email = (from p in db.users
                                      where p.active == true && p.project_id != null
                                      select new
                                      {
                                          p.project_id,
                                          p.user_email
                                      });

                    foreach (var savedUser in proj_email)
                    {
                        string[] theUser = savedUser.project_id.Split(new Char[] { ',' });

                        if (theUser != null)
                        {
                            foreach (var aUser in theUser)
                            {
                                if (aUser == proj.ToString())
                                {
                                    mail.To.Add(savedUser.user_email.Trim());
                                }
                            }
                        }
                    }

                    //Set the content
                    mail.Subject = "Monitoring and Evaluation: Reporting System";

                    System.Text.StringBuilder sbuilder = new System.Text.StringBuilder();
                    sbuilder.Append("Dear Project team,").AppendLine().AppendLine();
                    sbuilder.Append("Please note that the PMU has returned the ");
                    sbuilder.Append(pr.project.project1.Trim() + " " +
                        pr.report_period.report_period1.Trim() + " " + pr.year.year1.Trim());
                    sbuilder.Append(" quarterly report to you for updating.").AppendLine().AppendLine();

                    if (ProjectCommentTextBox.Text != string.Empty)
                    {
                        sbuilder.Append("CO comments include: ");
                        sbuilder.Append(ProjectCommentTextBox.Text).AppendLine().AppendLine();
                    }

                    sbuilder.Append("You can access the system here: http://www.ppu-reporting.net:8083/ ").AppendLine().AppendLine();
                    sbuilder.Append("Thank you").AppendLine().AppendLine();
                    sbuilder.Append("M&E team").AppendLine().AppendLine().AppendLine();
                    sbuilder.Append("*This email is automatically generated - please do not reply").AppendLine();

                    mail.Body = sbuilder.ToString();

                    //Send the message
                    var smtp = new SmtpClient
                    {
                        Host = "193.194.138.69",
                        Port = 25,
                        EnableSsl = true,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,
                        Credentials = new NetworkCredential(mail.From.Address, fromPassword)
                    };

                    ServicePointManager.ServerCertificateValidationCallback = delegate(
                            object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                    { return true; };
                    try
                    {
                        smtp.Send(mail);
                    }
                    catch (Exception ex)
                    {
                        ErrorLabel.Text = "MSG NOT SENT " + ex.Message + " " + ex.StackTrace;
                    }

                    //=============================================+
                    //                  END SEND MAIL              |
                    //=============================================+

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": Project Returned to Project team by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                    Session["App_Project"] = null;
                    Session["App_ReportPeriod"] = null;
                    Session["App_Year"] = null;

                    Response.Redirect("~/Amkeni_System/Project/Saved_Projects.aspx");
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            Session["App_Project"] = null;
            Session["App_ReportPeriod"] = null;
            Session["App_Year"] = null;
            */
        }
//===============================================================================================================
        protected void ArchiveButton_Click(object sender, EventArgs e)
        {
            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    ip_report pr = db.ip_report.SingleOrDefault(
                                            mypr => mypr.ip_id == proj &&
                                            mypr.year_id == yr &&
                                            mypr.report_period_id == rprt &&
                                            mypr.RFP_id == rfp);

                    pr.project_editor = AuthorTextBox.Text;

                    pr.archived = true;
                    pr.approved = false;
                    pr.archived_date = DateTime.Now;

                    db.SaveChanges();
                    //Just to make the code full proof
                    AuthorTextBox.Text = AuthorTextBox.Text;

                    Session["App_Project"] = null;
                    Session["App_ReportPeriod"] = null;
                    Session["App_Year"] = null;
                    Session["App_Call"] = null;

                    Response.Redirect("~/Amkeni_System/Archived_Project_Reports.aspx");
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;

                    //Just to make the code full proof
                    AuthorTextBox.Text = AuthorTextBox.Text;
                }
            }
            Session["App_Project"] = null;
            Session["App_ReportPeriod"] = null;
            Session["App_Year"] = null;
            Session["App_Call"] = null;
        }
//===============================================================================================================
        protected void PhotoGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            GridViewRow row = (GridViewRow)PhotoGridView.Rows[e.RowIndex];
            Label deleteID = (Label)row.FindControl("ID_Label");
            int delete = int.Parse(deleteID.Text.Trim());
            Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();
            try
            {
                ip_photo delPhoto = db.ip_photo.FirstOrDefault(d => d.photo_id == delete);

                //Delete the file
                string path = Server.MapPath("~/Amkeni_System/ip_photos/");
                string photoToDelete = path + delPhoto.name;

                //=========================================================
                // Add permissions to the file to enable file deletion    |
                //=========================================================
                try
                {
                    DirectorySecurity sec = Directory.GetAccessControl(photoToDelete);
                    //**Using this instead of the "Everyone" string means we work on non-English systems.
                    SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                    Directory.SetAccessControl(photoToDelete, sec);
                    if (File.Exists(photoToDelete))
                    {
                        File.Delete(photoToDelete);
                    }
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", "alert('Cannot Find The File to Delete')", true);
                }
                PhotoGridView.DataBind();
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//===============================================================================================================
        protected void PhotoGridView_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            PhotoCount(proj, rprt, yr, rfp);
        }
//===============================================================================================================
        protected void CFSButton_Click(object sender, EventArgs e)
        {
            try
            {
                ip_report cfs = db.ip_report.SingleOrDefault(
                                                data => data.ip_id == proj &&
                                                data.year_id == yr &&
                                                data.report_period_id == rprt &&
                                                data.RFP_id == rfp);
                if (cfs != null)
                {
                    decimal approvedBudget = decimal.Parse(ApprovedBudgetTextBox.Text.Trim());
                    decimal totalExpenditure = decimal.Parse(TotalTextBox.Text.Trim());
                    decimal balance = (approvedBudget - totalExpenditure);
                    decimal deliveryPercentage = Math.Round(((totalExpenditure / approvedBudget) * 100), 2, MidpointRounding.AwayFromZero);

                    cfs.approved_budget_cfs = approvedBudget;
                    cfs.total_cfs = totalExpenditure;
                    cfs.balance_cfs = balance;
                    cfs.delivery_cfs = deliveryPercentage;
                }
                else if (cfs == null)
                {
                    Response.Redirect("~/Amkeni_System/Project/Saved_Projects/");
                }
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
            finally
            {
                db.SaveChanges();
                populateReport(proj, rprt, yr, rfp);
                generateCumulativeFinancialSummaryPieChart(proj, rprt, yr, rfp);
            }
        }
//===============================================================================================================
        protected void PartnershipsButton_Click(object sender, EventArgs e)
        {
            try
            {
                Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();
                ip_report pc = db.ip_report.SingleOrDefault(
                                            pr => pr.ip_id == proj &&
                                            pr.year_id == yr &&
                                            pr.report_period_id == rprt &&
                                            pr.RFP_id == rfp);
                if (pc != null)
                {
                    pc.partnerships = PartnershipsTextBox.Text.Trim();
                    db.SaveChanges();
                }
                else if (pc == null)
                {
                    Response.Redirect("~/Amkeni_System/Project/Saved_Projects/");
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//===============================================================================================================
        protected void M_and_EButton_Click(object sender, EventArgs e)
        {
            try
            {
                //=============================+
                //  Add a new M&E activity     |
                //=============================+
                monitoring_and_evaluation me = new monitoring_and_evaluation();
                me.ip_id = proj;
                me.report_period_id = rprt;
                me.year_id = yr;
                me.RFP_id = rfp;
                me.activity = M_and_EActivityTextBox.Text.Trim();
                me.observation = ObservationTextBox.Text.Trim();
                me.recommendation = M_and_ERecommendationTextBox.Text.Trim();
                me.action_taken = ActionTakenTextBox.Text.Trim();
                db.monitoring_and_evaluation.Add(me);
                db.SaveChanges();

                MonitoringAndEvaluationGridView.DataBind();
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error on Monitoring and Evaluation : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//===============================================================================================================
        protected void RiskAndMitigationButton_Click(object sender, EventArgs e)
        {
            try
            {
                //============================================+
                //  Add a new Risk and Mitigation Measure     |
                //============================================+
                risk_and_mitigation rm = new risk_and_mitigation();
                rm.ip_id = proj;
                rm.report_period_id = rprt;
                rm.year_id = yr;
                rm.RFP_id = rfp;
                rm.risk = RiskTextBox.Text.Trim();
                rm.mitigation = MitigationTextBox.Text.Trim();
                db.risk_and_mitigation.Add(rm);
                db.SaveChanges();

                RiskAndMitigationGridView.DataBind();
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error on Risk and Mitigation : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
    }
}